import { Request, Response } from 'express'
import { controller, get, post } from '../decorator'
import { getResponseData } from '../utils'
interface BodyRequest extends Request {
  body: { [key: string]: string | undefined }
}
@controller('/api')
export class LoginController {
  static isLogin(req: BodyRequest) {
    return !!(req.session ? req.session.login : false)
  }

  @get('/isLogin')
  isLogin(req: BodyRequest, res: Response): void {
    const isLogin = LoginController.isLogin(req)
    res.json(getResponseData<responseResult.isLogin>(isLogin))
  }

  @post('/login')
  login(req: BodyRequest, res: Response): void {
    const isLogin = LoginController.isLogin(req)
    if (isLogin) {
      res.json(getResponseData<responseResult.login>(true))
    } else {
      if (req.body.password === '123' && req.session) {
        req.session.login = true
        res.json(getResponseData<responseResult.login>(true))
      } else {
        res.json(getResponseData<responseResult.login>(false, '登陆失败'))
      }
    }
  }

  @get('/logout')
  logout(req: BodyRequest, res: Response): void {
    if (req.session) req.session.login = false
    res.json(getResponseData<responseResult.logout>(true))
  }
}
